package com.yida.gwj.expend.outside.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.security.utils.SecurityUtils;
import com.yida.gwj.api.domain.GwjConfBusinessFlag;
import com.yida.gwj.api.domain.GwjConfStep;
import com.yida.gwj.api.service.RemoteGwjConfigService;
import com.yida.gwj.common.domain.GwjBaseCommunity;
import com.yida.gwj.common.domain.mq.MqSendResult;
import com.yida.gwj.common.enums.GwjBusinessFlagType;
import com.yida.gwj.common.handler.MqSendMessageHandler;
import com.yida.gwj.common.utils.GwjEnumUtils;
import com.yida.gwj.expend.outside.config.MaintenanceFundsBusinessConfiguration;
import com.yida.gwj.expend.outside.domain.GwjMaintenanceFundsBusinessBuild;
import com.yida.gwj.expend.outside.domain.GwjMaintenanceFundsBusinessHouse;
import com.yida.gwj.expend.outside.domain.GwjMaintenanceFundsBusinessInfo;
import com.yida.gwj.expend.outside.domain.dto.AddUseApplyFormDTO;
import com.yida.gwj.expend.outside.domain.dto.AllocatedAmountListDTO;
import com.yida.gwj.expend.outside.domain.dto.AllocatedAmountSelectDTO;
import com.yida.gwj.expend.outside.domain.dto.ApplicationReportDTO;
import com.yida.gwj.expend.outside.domain.dto.ApplyBaseInfoDTO;
import com.yida.gwj.expend.outside.domain.dto.ChangeSchemeDTO;
import com.yida.gwj.expend.outside.domain.dto.GetBusinessDetailDTO;
import com.yida.gwj.expend.outside.domain.dto.GwjMaintenanceFundsBusinessListDTO;
import com.yida.gwj.expend.outside.domain.dto.StepConfigInfoDTO;
import com.yida.gwj.expend.outside.domain.dto.TotalCostShareListDTO;
import com.yida.gwj.expend.outside.domain.message.MaintenanceFundsMqMessageBody;
import com.yida.gwj.expend.outside.domain.message.PreAcceptSubmitMessage;
import com.yida.gwj.expend.outside.domain.request.AllocatedAmountRequest;
import com.yida.gwj.expend.outside.domain.request.GwjMaintenanceFundsBusinessAddRequest;
import com.yida.gwj.expend.outside.domain.request.GwjMaintenanceFundsBusinessListRequest;
import com.yida.gwj.expend.outside.domain.request.ShareEquallyMoneyRequest;
import com.yida.gwj.expend.outside.enums.BusinessAttachmentServerTypeEnum;
import com.yida.gwj.expend.outside.enums.BusinessTypeEnum;
import com.yida.gwj.expend.outside.enums.FlagStatusEnum;
import com.yida.gwj.expend.outside.enums.MaintenanceFundsErrorEnum;
import com.yida.gwj.expend.outside.service.IGwjMaintenanceFundsBusinessAppropriateService;
import com.yida.gwj.expend.outside.service.IGwjMaintenanceFundsBusinessInfoService;
import com.yida.gwj.expend.outside.service.IGwjMaintenanceFundsBusinessInnerService;
import com.yida.gwj.expend.outside.service.IGwjMaintenanceFundsBusinessService;
import com.yida.gwj.expend.outside.service.IGwjMaintenanceFundsBusinessUrgentService;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;

/**
 * 公维金维修资金应急申请业务实现类
 *
 * @author liangp
 * @date 2023/04/24
 */
@Service
public class GwjMaintenanceFundsBusinessUrgentServiceImpl implements IGwjMaintenanceFundsBusinessUrgentService {
    private final Logger log = LoggerFactory.getLogger(GwjMaintenanceFundsBusinessUrgentServiceImpl.class);
    private final GwjBusinessFlagType businessFlagType = GwjBusinessFlagType.EXPEND_OUTSIDE_URGENT;
    @Autowired
    private IGwjMaintenanceFundsBusinessInfoService gwjMaintenanceFundsBusinessInfoService;
    @Autowired
    private IGwjMaintenanceFundsBusinessService gwjMaintenanceFundsBusinessService;
    @Autowired
    private IGwjMaintenanceFundsBusinessAppropriateService gwjMaintenanceFundsBusinessAppropriateService;
    @Autowired
    private RemoteGwjConfigService remoteGwjConfigService;
    @Autowired
    private MaintenanceFundsBusinessConfiguration maintenanceFundsBusinessConfiguration;
    @Autowired
    private MqSendMessageHandler mqSendMessageHandler;
    @Autowired
    private IGwjMaintenanceFundsBusinessInnerService maintenanceFundsBusinessInnerService;

    /**
     * 查询公维金维修资金业务列表
     *
     * @param maintenanceFundsBusinessListRequest 公维金维修资金业务
     * @return 公维金维修资金业务集合
     */
    @Override
    public List<GwjMaintenanceFundsBusinessListDTO> getGwjMaintenanceFundsBusinessList(GwjMaintenanceFundsBusinessListRequest maintenanceFundsBusinessListRequest) {
        return gwjMaintenanceFundsBusinessService.getGwjMaintenanceFundsBusinessList(maintenanceFundsBusinessListRequest);
    }

    /**
     * 新增应急申请业务
     *
     * @param gwjMaintenanceFundsBusinessAddRequest gwj维修基金业务请求
     * @return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AddUseApplyFormDTO addMaintenanceFundsBusinessForm(GwjMaintenanceFundsBusinessAddRequest gwjMaintenanceFundsBusinessAddRequest) {
        gwjMaintenanceFundsBusinessAddRequest.setBusinessFlagType(businessFlagType.getCode());
        gwjMaintenanceFundsBusinessAddRequest.setType(BusinessTypeEnum.URGENT_PREPARE.getCode());
        try {
            return gwjMaintenanceFundsBusinessService.addMaintenanceFundsBusinessForm(gwjMaintenanceFundsBusinessAddRequest);
        } catch (Exception e) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.URGENT_ADD_USE_APPLY) + e.getMessage());
        }
    }

    /**
     * 保存维护基金业务表单 更改公维金使用资金申请业务
     *
     * @param gwjMaintenanceFundsBusinessAddRequest gwj维修基金业务请求
     * @return int
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editMaintenanceFundsBusinessForm(GwjMaintenanceFundsBusinessAddRequest gwjMaintenanceFundsBusinessAddRequest) {
        try {
            return gwjMaintenanceFundsBusinessService.editMaintenanceFundsBusinessForm(gwjMaintenanceFundsBusinessAddRequest);
        } catch (ServiceException e) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.MAINTENANCE_FUNDS_OUTER_LISTENER) + e.getMessage());
        }
    }

    /**
     * 获取gwj维修基金业务详细信息
     *
     * @param bizId 业务标识
     * @return {@link GetBusinessDetailDTO}
     */
    @Override
    public GetBusinessDetailDTO getDetailMessage(Long bizId) {
        return gwjMaintenanceFundsBusinessService.getDetailMessage(bizId);
    }

    /**
     * 分摊金额-已选择
     *
     * @param allocatedAmountRequest
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public AllocatedAmountSelectDTO allocatedAmountList(AllocatedAmountRequest allocatedAmountRequest) {
        return gwjMaintenanceFundsBusinessService.allocatedAmountList(allocatedAmountRequest, GwjBusinessFlagType.EXPEND_OUTSIDE_URGENT);
    }

    /**
     * 使用申请-资金分摊-未选中列表
     *
     * @param allocatedAmountRequest 列表请求
     * @return 公维金维修资金业务
     */
    @Override
    public List<GwjMaintenanceFundsBusinessHouse> allocatedAmountCancelList(AllocatedAmountRequest allocatedAmountRequest) {
        return gwjMaintenanceFundsBusinessService.allocatedAmountCancelList(allocatedAmountRequest);
    }

    /**
     * 分摊金额-选中房屋操作
     *
     * @param allocatedAmountRequest
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public int allocatedAmountArrange(AllocatedAmountRequest allocatedAmountRequest) {
        return gwjMaintenanceFundsBusinessService.allocatedAmountArrange(allocatedAmountRequest);
    }

    /**
     * 分摊金额-取消选中房屋操作
     *
     * @param allocatedAmountRequest
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public int allocatedAmountCancel(AllocatedAmountRequest allocatedAmountRequest) {
        return gwjMaintenanceFundsBusinessService.allocatedAmountCancel(allocatedAmountRequest);
    }

    /**
     * 按类型平摊金额
     *
     * @param shareEquallyMoneyRequest
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public int shareEquallyMoney(ShareEquallyMoneyRequest shareEquallyMoneyRequest) {
        return gwjMaintenanceFundsBusinessService.shareEquallyMoney(shareEquallyMoneyRequest);
    }

    /**
     * 获取已选中楼栋信息
     *
     * @param bizId
     * @return 获取已选中楼栋信息
     */
    @Override
    public List<GwjMaintenanceFundsBusinessBuild> getSelectBuilds(Long bizId) {
        return gwjMaintenanceFundsBusinessService.getSelectBuilds(bizId);
    }

    /**
     * 查看申请报告
     *
     * @param bizId
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public ApplicationReportDTO getApplicationReport(Long bizId) {
        return gwjMaintenanceFundsBusinessService.getApplicationReport(bizId);
    }

    /**
     * 获取改造方案
     *
     * @param bizId 业务标识
     * @return {@link ChangeSchemeDTO}
     */
    @Override
    public ChangeSchemeDTO getTransformationPlan(Long bizId) {
        return gwjMaintenanceFundsBusinessService.getTransformationPlan(bizId);
    }

    /**
     * 查询决算费用分摊清册
     *
     * @param bizId 业务标识
     * @return int
     */
    @Override
    public TotalCostShareListDTO costList(Long bizId) {
        TotalCostShareListDTO totalCostShareListDTO = gwjMaintenanceFundsBusinessAppropriateService.costList(bizId, BusinessAttachmentServerTypeEnum.DETAILS_PROJECT_BUDGET_ALLOCATION);
        GwjMaintenanceFundsBusinessInfo gwjMaintenanceFundsBusinessInfo = gwjMaintenanceFundsBusinessInfoService.selectGwjMaintenanceFundsBusinessInfoByBusinessId(bizId);
        totalCostShareListDTO.setTotalSettlementAmount(gwjMaintenanceFundsBusinessInfo.getProjectBudgetAmount());
        return totalCostShareListDTO;
    }

    /**
     * 应急申请业务回填信息查询
     *
     * @param communityId 社区id
     * @return 应急申请业务回填信息
     */
    @Override
    public ApplyBaseInfoDTO getCommunity(Long communityId) {
        GwjBaseCommunity gwjBaseCommunity = maintenanceFundsBusinessInnerService.selectGwjBaseCommunityByGwjBaseCommunityId(communityId);
        if (ObjectUtil.isNull(gwjBaseCommunity)) {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_COMMUNITY_FAL) + "基础小区信息获取失败");
        }
        GwjConfBusinessFlag gwjConfBusinessFlag = remoteGwjConfigService.selectGwjConfBusinessFlagByBizFlagId(businessFlagType.getCode(), SecurityConstants.INNER).getData();
        if (ObjectUtil.isNull(gwjConfBusinessFlag)) {
            return null;
        }
        GwjConfStep confStep;
        try {
            R<List<GwjConfStep>> r = remoteGwjConfigService.selectGwjConfStepListByFlagId(businessFlagType.getCode(), SecurityConstants.INNER);
            if (R.isError(r)) {
                throw new ServiceException(r.getMsg());
            }
            if (ObjectUtil.isNull(r.getData())) {
                throw new ServiceException(r.getMsg());
            }
            confStep = r.getData().get(0);
        } catch (Exception e) {
            log.error("远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常,异常信息: [{}]", e);
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.GET_STEP_ID_FAL) + "远程调用 -> [remoteGwjConfigService][selectGwjConfStepListByFlagId]异常");
        }
        return new ApplyBaseInfoDTO() {
            {
                setCommunityName(gwjBaseCommunity.getCommunityName());
                setCompanyName(gwjBaseCommunity.getCompanyName());
                setContacts(SecurityUtils.getLoginUser().getSysOutsideUser().getRealName());
                setPhone(SecurityUtils.getLoginUser().getSysOutsideUser().getPhonenumber());
                setCategory(gwjConfBusinessFlag.getCategory());
                setBizFlagId(gwjConfBusinessFlag.getBizFlagId());
                setFlowId(gwjConfBusinessFlag.getFlowId());
                setFlowName(gwjConfBusinessFlag.getSubcategory());
                setStepId(confStep.getStepId());
                setStepName(confStep.getName());
                setApplicationUnitName(gwjBaseCommunity.getCompanyName());
            }
        };
    }

    /**
     * 提交数据到内网
     *
     * @param bizId 业务标识
     * @return int
     */
    @Override
    public int preAcceptSubmit(Long bizId) {
        PreAcceptSubmitMessage preAcceptSubmitMessage = gwjMaintenanceFundsBusinessService.preAcceptSubmit(bizId, BusinessAttachmentServerTypeEnum.getUrgentServerTypeList());
        String tag = maintenanceFundsBusinessConfiguration.urgentTagProperties().getPreAcceptSubmit();
        MqSendResult mqSendResult = mqSendMessageHandler.syncSend(new MaintenanceFundsMqMessageBody() {
            {
                setJsonMsg(JSONUtil.toJsonStr(preAcceptSubmitMessage));
                setServerIdentification(preAcceptSubmitMessage.getMaintenanceFundsBusiness().getServerIdentification());
            }
        }, new MaintenanceFundsBusinessConfiguration.MaintenanceFundsBusinessUrgentSendRequest(tag, null));
        if (mqSendResult.isSuccess()) {
            return FlagStatusEnum.SUC.getCode();
        } else {
            throw new ServiceException(GwjEnumUtils.getEnumConstantMsg(MaintenanceFundsErrorEnum.URGENT_PRE_ACCEPT_SUBMIT) + "公维金资金申请提交数据到内网MQ异常");
        }
    }

    /**
     * 导出房屋数据
     *
     * @param allocatedAmountRequest
     * @return 楼栋下房屋信息
     */
    @Override
    public List<AllocatedAmountListDTO> exportHouseList(AllocatedAmountRequest allocatedAmountRequest) {
        return gwjMaintenanceFundsBusinessService.exportHouseList(allocatedAmountRequest);
    }

    /**
     * 修改平摊金额
     *
     * @param shareEquallyMoneyRequest
     * @return AllocatedAmountSelectDTO
     */
    @Override
    public int shareEquallyMoneyUpdate(ShareEquallyMoneyRequest shareEquallyMoneyRequest) {
        return gwjMaintenanceFundsBusinessService.shareEquallyMoneyUpdate(shareEquallyMoneyRequest);
    }

    @Override
    public StepConfigInfoDTO getStepConfigInfo() {
        return gwjMaintenanceFundsBusinessService.getStepConfigInfo(businessFlagType);
    }

}
